//
//  WMImagesWatermarkedController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit
import PhotosUI
import AVKit

class WMImagesWatermarkedController: WMBaseViewController {
    
    @IBOutlet weak var adView: UIView!
    @IBOutlet weak var adViewH: NSLayoutConstraint!
    @IBOutlet weak var videoBacView: UIView!
    @IBOutlet weak var iphoneBtn: UIButton!
    @IBOutlet weak var ipadBtn: UIButton!
    
    
    private var player: AVPlayer?
    private var playerLayer: AVPlayerLayer?
    
    var isInit = false
    var needShowAd = false
    var bannerView: BUNativeExpressBannerView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        isNavigationBarHidden = true
        
        // 设置视频播放
        setupVideoPlayer()
        
        NotificationCenter.default.addObserver(forName: .adInitSuccessed) { [weak self] _ in
            guard let self = self else { return }
            self.isInit = true
            self.initAd()
        }
        if initAdSuccess && !isInit {
            isInit = true
            initAd()
        }
        
        if UIDevice.current.userInterfaceIdiom == .phone {
            print("当前设备是 iPhone")
            self.iphoneBtn.isHidden = false
            self.ipadBtn.isHidden = true
        } else if UIDevice.current.userInterfaceIdiom == .pad {
            print("当前设备是 iPad")
            self.iphoneBtn.isHidden = true
            self.ipadBtn.isHidden = false
        }
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 视图显示时开始播放
        player?.play()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 视图消失时暂停播放
        player?.pause()
    }
    
    deinit {
        // 移除通知观察者
        NotificationCenter.default.removeObserver(self)
    }
    
    // 设置视频播放器
    private func setupVideoPlayer() {
        // 获取视频文件路径
        guard let videoPath = Bundle.main.path(forResource: "picture_remove_watermark", ofType: "mp4") else {
            print("视频文件未找到")
            return
        }
        
        let videoURL = URL(fileURLWithPath: videoPath)
        player = AVPlayer(url: videoURL)
        
        // 创建播放器图层
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.videoGravity = .resizeAspectFill
        playerLayer?.frame = CGRect(x: 0, y: 0, width: kScreenWidth - 60, height: kScreenWidth - 60)
        
        // 添加到视图
        if let playerLayer = playerLayer {
            videoBacView.layer.addSublayer(playerLayer)
        }
        
        // 设置循环播放
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime,
                                               object: player?.currentItem,
                                               queue: .main) { [weak self] _ in
            self?.player?.seek(to: .zero)
            self?.player?.play()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 更新播放器图层尺寸
        playerLayer?.frame = videoBacView.bounds
    }
    
    //立即去水印
    @IBAction func immediatelyWatermarkBtnClickAction(_ sender: Any) {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            checkAuthority()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.checkAuthority()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
    }
    
    func checkAuthority() {
        //校验权限
        checkAlbunAuthority { granted in
            if (granted) {
                self.callingAlbums()
            }else {
                KBMerPrtmissionView.show(type: .PhotoLibrary)
                return;
            }
        }
    }
    
    //调用相册
    func callingAlbums(){
        if #available(iOS 14, *) {
            // iOS 14+ 使用 PHPicker
            var config = PHPickerConfiguration()
            config.selectionLimit = 1 // 选择1张图片
            config.filter = .images   // 只显示图片
            
            let picker = PHPickerViewController(configuration: config)
            picker.delegate = self
            present(picker, animated: true)
        } else {
            // iOS 13及以下使用 UIImagePickerController
            let picker = UIImagePickerController()
            picker.sourceType = .photoLibrary
            picker.delegate = self
            present(picker, animated: true)
        }
    }
    
    
    func requestPermission(_ complation: @escaping (Bool, String)->Void) {
        let picfree = UserDefaults.standard.value(forKey: UserDefaultsKey.picfree) as? Int ?? 0
        let useCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzTotalUseCount) as? Int ?? 0
        complation(useCount < picfree, "")
        //        WMAgentApi.shared.requestApi(ApiEnum.permission) { res in
        //            let code: String = res["code"] as! String
        //            let message: String? = res["message"] as? String
        //            complation((code == "200" || code == "0"), message.or(""))
        //        }
    }
    
}

// MARK: - PHPickerViewControllerDelegate (iOS 14+)
@available(iOS 14, *)
extension WMImagesWatermarkedController: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true)
        
        guard let result = results.first else { return }
        
        // 加载选中的图片
        result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (image, error) in
            DispatchQueue.main.async {
                if let image = image as? UIImage {
                    let fixVC = WMConfirmFixViewController()
                    fixVC.image = image
                    self?.navigationController?.pushViewController(fixVC, animated: true)
                }
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate (iOS 13及以下)
extension WMImagesWatermarkedController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let image = info[.originalImage] as? UIImage {
            let fixVC = WMConfirmFixViewController()
            fixVC.image = image
            self.navigationController?.pushViewController(fixVC, animated: true)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

extension WMImagesWatermarkedController: BUNativeExpressBannerViewDelegate {
    
    func initAd() {
        if !isInit { return }
        bannerView = BUNativeExpressBannerView(slotID: "970745833", rootViewController: self, adSize: CGSize(width: 300, height: 75))
        bannerView!.frame = CGRect(x: (kScreenWidth - 300 - 32) / 2, y: 15, width: 300, height: 75)
        bannerView!.delegate = self
        bannerView!.loadAdData()
    }
    
    func nativeExpressBannerAdViewDidLoad(_ bannerAdView: BUNativeExpressBannerView) {
        let isMember = UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0
        let showAd = UserDefaults.standard.value(forKey: UserDefaultsKey.showad) as? Int ?? 1
        if isMember == 1 || showAd == 0 {
            needShowAd = false
            bannerAdView.removeFromSuperview()
            adViewH.constant = 0
        }else {
            needShowAd = true
            adView.addSubview(bannerAdView)
            adViewH.constant = 100
        }
    }
    
    func nativeExpressBannerAdViewDidRemoved(_ bannerAdView: BUNativeExpressBannerView) {
        needShowAd = false
        bannerAdView.removeFromSuperview()
        adViewH.constant = 0
    }
    
    func nativeExpressBannerAdView(_ bannerAdView: BUNativeExpressBannerView, didLoadFailWithError error: Error?) {
        
    }
    
}
